//
//  YQStatusListViewModel.m
//  WeiboOC
//
//  Created by yang on 15/11/19.
//  Copyright © 2015年 yang. All rights reserved.
//

#import "YQStatusListViewModel.h"
#import "YQStatus.h"
static NSDictionary *parameters;
@implementation YQStatusListViewModel
+ (void)loadDataSince_id:(NSNumber*)since_id max_id:(NSNumber*)max_id finished:(void (^)(NSArray * array))finished
{
    YQUserAccountViewModel *user = [[YQUserAccountViewModel alloc]init];
    if (!user.tooken) {
        [SVProgressHUD showErrorWithStatus:@"您暂未登陆"];
        return;
    }
    NSString* urlString = @"2/statuses/home_timeline.json";
    
    if (since_id > 0) {
        parameters = @{@"access_token":user.tooken, @"since_id":since_id};
    }else if (max_id > 0) {
        long long m = [max_id longLongValue];
        parameters = @{@"access_token":user.tooken, @"max_id":@(m - 1)};
    }else{
        parameters = @{@"access_token":user.tooken};
    }
    NSLog(@"%@",parameters);
    [[YQNetworkTools sharedTools] requestJsonDict:GET urlString:urlString parameters:parameters finished:^(id dict, NSError *error) {
        if (error) {
            finished(nil);
            return ;
        }
        NSMutableArray *list = [NSMutableArray array];
        NSArray *a = dict[@"statuses"];
        for (NSDictionary *dict in a) {
            YQStatus *status = [YQStatus statusWithDict:dict];
            [list addObject:status];
        }
        [YQStatusListViewModel cacheStatusImage:list finished:^(NSArray *array) {
            finished(array);
        }];
    }];
}
//单张图片缓存
+ (void)cacheStatusImage:(NSArray *)array finished:(void (^)(NSArray *array))finished{
    if (array.count == 0) {
        finished(array);
        return;
    }
    dispatch_group_t group = dispatch_group_create();
    for (YQStatus *status in array) {
        NSArray *urlArr = status.url;
        
        if (urlArr.count == 1) {
            dispatch_group_enter(group);
            for (NSURL *url in urlArr) {
                [[SDWebImageManager sharedManager]downloadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    dispatch_group_leave(group);
                }];
          }
         
        }
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        finished(array);
    });
   
    
}
@end
